#!/bin/bash
#liang.wei@outlook.com
set -e
op=$1  #limit or ulimit
container=$2  #container name or id
container_nic=$3 #container nic name
limit=$4  # Mbits/s
if [ -z $1 ] || [ -z $2 ]; then
    echo "####ovs-limit is limit container nic commands, bandwidth default Mbps####"
    echo "ovs-limit  limit <container name> <container_nic> <bandwidth>"
    echo "ovs-limit  ulimit <container name> <container_nic>"
    #echo "Example2: I want delete network limit in the container:test"
    echo "Example limit container gw-8.254 5M: ovs-limit  limit eth2 gw-8.254 5"
    echo "Example clear network limit: ovs-limit  ulimit  gw-8.254 eth2"
    exit 1
fi
#if [ -z $4 ];then
#    echo "limit not null"
#fi
if [ -z $3 ];then
    echo "container_nic not null"
    exit 1
fi
if [ `docker inspect --format "{{.State.Pid}}" $container &>>/dev/null && echo 0 || echo 1` -eq 1 ];then
echo "no this container:$container"
exit 1
fi
ovs_prefix='v'$container_nic'pl'
container_id=`docker inspect --format "{{.State.Pid}}" $container`
device_name=`echo ${ovs_prefix}${container_id}`
if [ $op == 'limit' ];then
if [ -z $4 ];then
    echo "bandwidth not null"
    exit 1
fi
for v in $device_name; do
    ovs-vsctl set interface $v ingress_policing_rate=$((limit*1000))
    ovs-vsctl set interface $v ingress_policing_burst=$((limit*100))
    ovs-vsctl set port $v qos=@newqos -- --id=@newqos create qos type=linux-htb queues=0=@q0 other-config:max-rate=$((limit*1000000)) -- --id=@q0 create queue other-config:min-rate=$((limit*1000000)) other-config:max-rate=$((limit*1000000)) &>>/dev/null && echo 'modify success!' || echo 'modify fail!'
done
elif [ $op == 'ulimit' ];then
for v in $device_name; do
    ovs-vsctl set interface $v ingress_policing_rate=0
    ovs-vsctl set interface $v ingress_policing_burst=0
    ovs-vsctl clear Port $v qos &>>/dev/null && echo 'modify success!' || echo 'modify fail!'
done
fi
